<template>
  <px-dialog
    v-model="dialogVisible"
    class="equip-dialog-wrap"
    :title="data ? '编辑工作项' : '新增工作项'"
    width="50%"
    align-center
    @close="handleCancel"
  >
    <px-form ref="formRef" :model="queryParams" label-position="right" label-width="80px">
      <px-row :gutter="16">
        <px-col :span="24">
          <px-form-item prop="itemType" label="类型" :rules="[{ required: true, message: '类型不能为空', trigger: 'change' }]">
            <px-select v-model="queryParams.itemType" :disabled="data?.finishStatus === 'Done'" placeholder="请选择巡检内容" filterable clearable>
              <px-option v-for="item in TYPE_CONFIG" :key="item.value" :label="item.label" :value="item.value" />
            </px-select>
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item prop="time" label="时间" :rules="[{ required: true, message: '时间不能为空', trigger: 'change' }]">
            <px-date-picker
              v-model="queryParams.time"
              :disabled="data?.finishStatus === 'Done'"
              style="width: 100%"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetime"
              placeholder="请选择时间"
            />
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <!-- 地块 -->
          <FactoryArea
            :disabled="data?.finishStatus === 'Done'"
            :factoryArea="queryParams.facCode"
            propValue="facCode"
            :isRequired="true"
            @changeFactoryArea="changeFactoryArea"
          />
        </px-col>
        <px-col :span="24">
          <px-form-item prop="area" label="区域" :rules="[{ required: true, message: '区域不能为空', trigger: 'change' }]">
            <px-cascader
              ref="cascaderRef"
              v-model="queryParams.area"
              :disabled="data?.finishStatus === 'Done'"
              filterable
              clearable
              style="width: 100%"
              :options="positionCodesList"
              :props="cascaderProps"
              placeholder="请选择区域"
              collapse-tags
              collapse-tags-tooltip
              @change="changeCheckArea"
              @focus="focusPositionCodes"
            />
          </px-form-item>
        </px-col>
        <px-col :span="24">
          <px-form-item prop="reason" label="原因" :rules="[{ required: true, message: '原因不能为空', trigger: 'change' }]">
            <px-input
              v-model="queryParams.reason"
              :disabled="data?.finishStatus === 'Done'"
              type="textarea"
              placeholder="请输入原因"
              clearable
              :autosize="{ minRows: 2, maxRows: 4 }"
              maxlength="1000"
            />
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item prop="applicantId" label="申请人员" :rules="[{ required: true, message: '申请人员不能为空', trigger: 'change' }]">
            <px-select-v2
              v-model="queryParams.applicantId"
              :disabled="data?.finishStatus === 'Done'"
              :options="userList"
              filterable
              clearable
              placeholder="请输入申请人员姓名或工号"
              remote
              :remote-method="getUserList"
              @change="handleApplicantChange"
              @visible-change="val => (val ? getUserList() : [])"
            />
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item prop="deptName" label="申请部门">
            <px-input v-model="queryParams.deptName" disabled placeholder="请输入申请部门" @blur="queryParams.reason = $event.target.value.trim()" />
          </px-form-item>
        </px-col>
        <px-col :span="24">
          <px-form-item prop="ercId" label="ERC人员" :rules="[{ required: true, message: 'ERC人员不能为空', trigger: 'change' }]">
            <px-select-v2
              v-model="queryParams.ercId"
              :disabled="data?.finishStatus === 'Done'"
              :options="personList"
              filterable
              clearable
              placeholder="请选择ERC人员"
              @focus="getPersonList"
            />
          </px-form-item>
        </px-col>
        <px-col :span="24">
          <px-form-item prop="remark" label="备注" :rules="[{ required: true, message: '备注不能为空', trigger: 'change' }]">
            <px-input
              v-model="queryParams.remark"
              clearable
              type="textarea"
              placeholder="请输入备注"
              :autosize="{ minRows: 2, maxRows: 4 }"
              maxlength="1000"
            />
          </px-form-item>
        </px-col>
      </px-row>
      <px-form-item class="align-right">
        <px-button @click="handleCancel">取消</px-button>
        <px-button type="primary" @click="handleSubmit(formRef)">保存</px-button>
      </px-form-item>
    </px-form>
  </px-dialog>
</template>

<script setup lang="ts">
import { queryCheckAreaTree } from "@/api/erc/inspectPlan";
import { queryUserList, save, update } from "@/api/erc/workItem";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import { FactoryArea } from "@/views/erc/inspect/components/index";
import { cloneDeep } from "@pureadmin/utils";
import { PxMessage, dayjs } from "px-ui";
import { onMounted, ref, watch } from "vue";
import { TYPE_CONFIG } from "../const";
const props = defineProps(["data", "positionList"]);
const dialogVisible = defineModel("dialogVisible");
const formRef = ref();
const emits = defineEmits(["refresh"]);
const queryParams = ref<any>({
  time: "",
  positionCodes: "",
  remark: ""
});
const types = ref<any[]>([]);
const cascaderProps = {
  children: "children",
  label: "name",
  value: "id",
  // checkStrictly: true,
  multiple: true
};
watch(dialogVisible, () => {
  if (!dialogVisible.value) {
    queryParams.value = {};
    formRef.value.resetFields();
  } else {
    queryParams.value.time = dayjs().format("YYYY-MM-DD HH:mm:ss");
  }
});
watch(
  () => [props.data, dialogVisible],
  () => {
    if (props.data && dialogVisible.value) {
      queryParams.value = cloneDeep({ ...props.data, area: props.data.positionCodes });
      userList.value = [
        {
          label: queryParams.value.applicantName,
          value: queryParams.value.applicantId
        }
      ];
      personList.value = [
        {
          label: queryParams.value.ercName,
          value: queryParams.value.ercId
        }
      ];
    }
  }
);
// 获取ERC人员
const personList = ref([]);
const getPersonList = async () => {
  const data = await getEmployeeIdAndName(["HSE", "ISEP", "ERC&FP"]);
  const newData = data || [];
  personList.value = newData;
};
// 获取申请人员
const userList = ref<any[]>([]);
const getUserList = async (val?: string) => {
  const res = await queryUserList({ name: val, pageSize: val ? undefined : 9999 });
  const newData = (res.data || []).map(item => ({ label: item.username, value: item.userId, deptName: item.deptName }));
  userList.value = newData;
};
// 申请人员改变
const handleApplicantChange = val => {
  const item = userList.value.find(item => item.value === val);
  queryParams.value.deptName = item?.deptName;
};
// 地块
const changeFactoryArea = val => {
  queryParams.value.facCode = val;
  queryParams.value.area = [];
};
onMounted(() => {
  // positionCodesList.value = props.positionList;
  focusPositionCodes();
});
// 获取巡检区域
const positionCodesList = ref([]);
const focusPositionCodes = async () => {
  const data = await queryCheckAreaTree({ facCode: queryParams.value.facCode });
  positionCodesList.value = data || [];
};
// 巡检区域改变
const changeCheckArea = val => {
  if (val && val.length > 0) {
    queryParams.value.positionCodes = val.map(item => {
      const ind = item.length - 1;
      return item[ind];
    });
  } else {
    queryParams.value.positionCodes = [];
  }

  // cascaderRef.value.togglePopperVisible();
};
const handleSubmit = async formEl => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      const { area, time, ...others } = queryParams.value;
      const data = { ...others, time: dayjs(time).format("YYYY-MM-DD HH:mm:ss") };
      if (!props.data?.id) {
        await save(data);
        PxMessage.success("提交成功");
      } else {
        await update({ ...props.data, ...data });
        PxMessage.success("编辑成功");
      }
      emits("refresh");
      dialogVisible.value = false;
    }
  });
};
const handleCancel = () => {
  dialogVisible.value = false;
  queryParams.value = {};
  formRef.value.resetFields();
};
</script>

<style lang="scss" scoped>
@import url("../../../scss/add-dialog.scss");

.align-right {
  :deep(.px-form-item__content) {
    justify-content: flex-end;
  }
}
</style>
